import { conn } from "@beshell/conn-ts/Connection"
import { Stud } from "../Stud"
import { Usage } from "../StudUsage"
import { Cable } from "./Cable"

export class I2C extends Cable {
    constructor(title: string, public name: string, scl?: Stud, sda?: Stud, baudrate: number=400000) {
        super("i2c", title, name, baudrate)
        this.mapDefaultHostStuds[Usage.i2cscl] = scl
        this.mapDefaultHostStuds[Usage.i2csda] = sda
    }
    
    write(data: number[]): void {
        this.writeTo(data[0], data.slice(1))
    }
    writeTo(device: number, data: number[]) {
        if(!conn.isConnected)
            return
        let code = `${this.name}.writeTo(${device}, [${data.join(',')}])\n`
        conn.active?.write(code)
    }
    async readFrom(device: number, length: number) {
        if(!conn.isConnected)
            return
        let code = `resolve(${this.name}.readFrom(${device}, ${length}))\n`
        return await conn.console.call(code)
    }
    
    public generateSetupCode(indent=0, freeFirst=false){
        let sda = this.mapHostStuds[Usage.i2csda]
        let scl = this.mapHostStuds[Usage.i2cscl]
        if( !sda || !scl)  {
            return ''
        }
        return `${"\t".repeat(indent)}beapi.i2c.setup(${this.name}, ${sda.gpio.name()}, ${scl.gpio.name()}, ${this.baudrate})\n`
    }
}
